<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="14">
          <!-- 搜索与添加区域 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="dialogVisible = !dialogVisible"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="butModify(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeDele(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <!-- 分配角色按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="butrole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="70px"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="dialogModify"
      width="50%"
      @close="modifyClose"
      :lock-scroll="false"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="userModify"
        :rules="rules"
        ref="userModify"
        label-width="70px"
        status-icon
      >
        <el-form-item label="用户名">
          <el-input v-model="userModify.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="userModify.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userModify.email"></el-input>
        </el-form-item>
      </el-form>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModify = false">取 消</el-button>
        <el-button type="primary" @click="butdialog('userModify')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="roleModify"
      width="50%"
      :lock-scroll="false"
      @close="roleClose"
    >
      <!-- 内容主体区域 -->
      <p>当前的用户： {{ roleList.username }}</p>
      <p>当前的角色： {{ roleList.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="rolelder" placeholder="请选择">
          <el-option
            v-for="item in userRoloeslist"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <!--  底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleModify = false">取 消</el-button>
        <el-button type="primary" @click="butRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      } else {
        cb(new Error("请输入合法的邮箱"));
      }
    };

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      } else {
        cb(new Error("请输入合法的手机号"));
      }
    };
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 搜索字段传给后端获取数据
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 10
      },
      userlist: [],
      // 显示一共有多少条数据
      total: 0,
      // 控制对话框的显示与隐藏
      dialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      dialogModify: false,
      // 修改对话框用户信息数据
      userModify: {},
      // 控制分配角色对话框的显示与隐藏
      roleModify: false,
      // 分配角色数据
      roleList: {},
      // 分配角色列表数据
      userRoloeslist: [],
      // 分配角色下拉框已选的值
      rolelder: "",
      // 添加用户表单的数据
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      // 表单的验证规则
      rules: {
        // 验证用户名是否合法
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        // 验证密码是否合法
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        // 验证邮箱是否合法
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        // 验证手机号是否合法
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    //获取列表数据接口
    async getUserList() {
      const result = await this.$http.get("users", {
        params: this.queryInfo
      });
      this.userlist = result.data.users;
      this.total = result.data.total;
    },
    // 监听 pagesize 改变的事件  一页显示多少条数据
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //监听 switch 开关状态的改变
    async userStateChange(val) {
      const result = await this.$http.put(
        `users/${val.id}/state/${val.mg_state}`
      );
      if (result.meta.status == 200) {
        this.$message.success("修改成功！");
      } else {
        val.mg_state = !val.mg_state;
        this.$message.error("修改失败！");
      }
    },
    // 监听添加用户对话框关闭事件
    dialogClose() {
      // 当对话框关闭时会触发表单重置事件
      this.$refs.ruleForm.resetFields();
    },
    modifyClose() {
      // 当修改对话框关闭时会触发表单重置事件
      this.$refs.userModify.resetFields();
    },
    // 点击确定按钮进行添加新用户
    addUser(ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.post("users", this.ruleForm);
          if (result.meta.status == 201) {
            this.$message.success("用户创建成功！");
            this.dialogVisible = !this.dialogVisible; //创建成功对话框隐藏
            this.getUserList(); //重新加载列表数据
          }
        } else {
          this.$message.error("用户创建失败！");
        }
      });
    },
    // 点击修改按钮获取当前用户信息接口
    async butModify(id) {
      const result = await this.$http.get("users/" + id);
      if (result.meta.status == 200) {
        console.log("获取成功");
        this.userModify = result.data;
        console.log(this.userModify);
      } else {
        this.$message.error("用户信息获取失败！");
      }
      this.dialogModify = !this.dialogModify;
    },
    // 修改用户修改信息并提交接口
    butdialog(userModify) {
      this.$refs[userModify].validate(async valid => {
        if (valid) {
          // 验证通过发起网络接口请求
          const result = await this.$http.put(
            "users/" + this.userModify.id,
            this.userModify
          );
          if (result.meta.status == 200) {
            this.$message.success("用户信息修改成功！");
            this.dialogModify = !this.dialogModify; //创建成功对话框隐藏
            this.getUserList(); //重新加载列表数据
          }
        } else {
          this.$message.error("用户创建失败！");
        }
      });
    },
    // 根据ID删除对应的用户信息
    async removeDele(id) {
      // 弹框询问用户是否删除数据
      const res = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          lockScroll: false
        }
      ).catch(err => err);
      console.log(res);
      console.log(id);
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (res == "cancel") {
        this.$message.warning("您已取消删除操作！");
      } else {
        const reslut = await this.$http.delete("users/" + id);
        if (reslut.meta.status == 200) {
          this.getUserList();
          this.$message.success("您已删除该用户！");
        } else {
          this.$message.error("删除失败！");
        }
      }
    },
    // 分配角色接口
    async butrole(row) {
      this.roleModify = !this.roleModify;
      this.roleList = row;
      const result = await this.$http.get("roles");
      this.userRoloeslist = result.data;
      console.log(this.userRoloeslist);
    },
    // 提交分配角色信息接口
    async butRoles() {
      const result = await this.$http.put(`users/${this.roleList.id}/role`, {
        rid: this.rolelder
      });
      if (result.meta.status == 200) {
        console.log(this.roleList);
        this.$message.success("分配角色成功！");
        this.getUserList();
      } else {
        this.$message.error("分配角色失败！");
      }
      this.roleModify = !this.roleModify;
    },
    // 监听分配角色对话框事件
    roleClose() {
      // 当对话框关闭时会触发表单重置事件
      this.rolelder = "";
    }
  },
  created() {
    this.getUserList();
  }
};
</script>

<style lang="stylus" scoped></style>
